<template>
  <div class="resident">
    <van-popup round v-model="popupShow" position="bottom">
      <template v-if="popupState == 'picker'">
        <!-- <van-picker show-toolbar :columns="pickerData" @confirm="pickerConfirm" @cancel="pickerCancel"><template
            v-if="pickerType == 'nationality'" #columns-top>
            <van-search v-model="data.search" placeholder="可模糊检索" @input="searchChange(pickerType)" class="search-body">
            </van-search>
          </template></van-picker> -->
        <van-picker
          show-toolbar
          :columns="pickerData"
          @confirm="pickerConfirm"
          @cancel="pickerCancel"
        ></van-picker>
      </template>
      <template v-if="popupState == 'datePicker'"
        ><van-datetime-picker
          type="date"
          title="选择年月日"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="datePickerConfirm"
          @cancel="datePickerCancel"
        >
        </van-datetime-picker>
      </template>
      <template v-if="popupState == 'cascader'">
        <van-cascader
          :field-names="fieldNames"
          v-model="cascaderValue"
          title="请选择所属区域"
          :options="cascadeOptions"
          active-color="#D58913"
          @finish="cascaderFinish"
          @close="cascaderClose"
        />
      </template>
    </van-popup>

    <div class="resident-inner">
      <van-form
        label-width="110px"
        ref="form"
        scroll-to-error
        :show-error-message="false"
        @failed="onFailed"
        @submit="onSubmit"
      >
        <div class="card">
          <div class="card-bar">
            <div class="card-bar-title">居住人信息</div>
          </div>
          <div class="card-container">
            <van-field
              v-model="formData.name"
              required
              clearable
              maxlength="20"
              :rules="[{ required: true, message: '请检查姓名' }]"
              name="name"
              placeholder="请输入姓名"
            >
              <template #label>
                <div class="field-title">姓名</div>
              </template>
            </van-field>
            <!-- <van-field readonly clickable is-link name="nationality_name" :value="formData.nationality_name"
              placeholder="点击选择" @click="pickerChange('nationality')" required
              :rules="[{ required: true, message: '请检查国籍' }]">
              <template #label>
                <div class="field-title">国籍</div>
              </template>
            </van-field> -->
            <van-field
              readonly
              clickable
              is-link
              name="origin_name"
              :value="formData.origin_name"
              placeholder="点击选择"
              @click="pickerChange('origin')"
              required
              :rules="[{ required: true, message: '请检查证件类型' }]"
            >
              <template #label>
                <div class="field-title">证件类型</div>
              </template>
            </van-field>
            <!-- <van-field v-model="formData.card_no" required :readonly="route.isFirst == '1' || !!route.id" maxlength="18"
              :rules="[
                {
                  required: true,
                  validator: cardNoValidator,
                  message:
                    formData.nationality == 'CN'
                      ? '请检查身份证号'
                      : '请检查证件号码',
                },
              ]" name="card_no" :placeholder="
                formData.nationality == 'CN'
                  ? '请输入身份证号'
                  : '请输入证件号码'
              " @blur="cardNoChange">
              <template #label>
                <div class="field-title">
                  {{ formData.nationality == 'CN' ? '身份证号' : '证件号码' }}
                </div>
              </template>
            </van-field> -->
            <van-field
              v-model="formData.card_no"
              required
              :readonly="route.isFirst == '1' || !!route.id"
              maxlength="18"
              :rules="[
                {
                  required: true,
                  validator: cardNoValidator,
                  message:
                    formData.origin == '身份证'
                      ? '请检查身份证号'
                      : '请检查证件号码',
                },
              ]"
              name="card_no"
              :placeholder="
                formData.origin == '身份证'
                  ? '请输入身份证号'
                  : '请输入证件号码'
              "
              @blur="cardNoChange"
            >
              <template #label>
                <div class="field-title">
                  {{ formData.origin == '身份证' ? '身份证号' : '证件号码' }}
                </div>
              </template>
            </van-field>
            <van-field
              readonly
              clickable
              is-link
              v-model="formData.birthday"
              required
              type="birthday"
              :rules="[{ required: true, message: '请检查出生日期' }]"
              name="birthday"
              label="出生日期"
              placeholder="点击选择"
              @click="pickerChange('date')"
            >
              <template #label>
                <div class="field-title">出生日期</div>
              </template>
            </van-field>
            <van-field
              v-model="formData.tel"
              required
              clearable
              maxlength="11"
              :rules="[{ required: true, message: '请检查联系方式' }]"
              name="tel"
              type="tel"
              placeholder="请输入联系方式"
            >
              <template #label>
                <div class="field-title">联系方式</div>
              </template>
            </van-field>
            <van-field
              name="sex"
              required
              :rules="[{ required: true, message: '请检查性别' }]"
            >
              <template #label>
                <div class="field-title">性别</div>
              </template>
              <template #input>
                <van-radio-group
                  v-model="formData.sex"
                  checked-color="#D58913"
                  direction="horizontal"
                >
                  <van-radio name="1">男</van-radio>
                  <van-radio name="2">女</van-radio>
                </van-radio-group>
              </template>
            </van-field>
            <van-field name="medicalHistoryArr">
              <template #label>
                <div class="field-title">既往病史</div>
              </template>
              <template #input>
                <van-checkbox-group
                  v-model="formData.medicalHistoryArr"
                  @change="medicalHistoryChange"
                  direction="horizontal"
                >
                  <van-row>
                    <van-col span="12">
                      <van-checkbox
                        checked-color="#D58913"
                        name="无"
                        shape="square"
                        :disabled="
                          !noHistory && formData.medicalHistoryArr.length > 0
                        "
                        >无</van-checkbox
                      >
                    </van-col>
                    <van-col span="12">
                      <van-checkbox
                        checked-color="#D58913"
                        name="营养不良"
                        shape="square"
                        :disabled="
                          noHistory && formData.medicalHistoryArr.length > 0
                        "
                        >营养不良</van-checkbox
                      >
                    </van-col>
                    <van-col span="12">
                      <van-checkbox
                        checked-color="#D58913"
                        name="贫血"
                        shape="square"
                        :disabled="
                          noHistory && formData.medicalHistoryArr.length > 0
                        "
                        >贫血</van-checkbox
                      >
                    </van-col>
                    <van-col span="12">
                      <van-checkbox
                        checked-color="#D58913"
                        name="高血压"
                        shape="square"
                        :disabled="
                          noHistory && formData.medicalHistoryArr.length > 0
                        "
                        >高血压</van-checkbox
                      >
                    </van-col>
                    <van-col span="12">
                      <van-checkbox
                        checked-color="#D58913"
                        name="糖尿病"
                        shape="square"
                        :disabled="
                          noHistory && formData.medicalHistoryArr.length > 0
                        "
                        >糖尿病</van-checkbox
                      >
                    </van-col>
                    <van-col span="12">
                      <van-checkbox
                        checked-color="#D58913"
                        name="心脑血管疾病"
                        shape="square"
                        :disabled="
                          noHistory && formData.medicalHistoryArr.length > 0
                        "
                        >心脑血管疾病</van-checkbox
                      >
                    </van-col>
                    <van-col span="12">
                      <van-checkbox
                        checked-color="#D58913"
                        name="哮喘"
                        shape="square"
                        :disabled="
                          noHistory && formData.medicalHistoryArr.length > 0
                        "
                        >哮喘</van-checkbox
                      >
                    </van-col>
                    <van-col span="12">
                      <van-checkbox
                        checked-color="#D58913"
                        name="慢性肺部疾病"
                        shape="square"
                        :disabled="
                          noHistory && formData.medicalHistoryArr.length > 0
                        "
                        >慢性肺部疾病</van-checkbox
                      >
                    </van-col>
                    <van-col span="12">
                      <van-checkbox
                        checked-color="#D58913"
                        name="肿瘤"
                        shape="square"
                        :disabled="
                          noHistory && formData.medicalHistoryArr.length > 0
                        "
                        >肿瘤</van-checkbox
                      >
                    </van-col>
                    <van-col span="12">
                      <van-checkbox
                        checked-color="#D58913"
                        name="肺结核"
                        shape="square"
                        :disabled="
                          noHistory && formData.medicalHistoryArr.length > 0
                        "
                        >肺结核</van-checkbox
                      >
                    </van-col>
                    <van-col span="12">
                      <van-checkbox
                        checked-color="#D58913"
                        name="慢性肾病"
                        shape="square"
                        :disabled="
                          noHistory && formData.medicalHistoryArr.length > 0
                        "
                        >慢性肾病</van-checkbox
                      >
                    </van-col>
                    <van-col span="12">
                      <van-checkbox
                        checked-color="#D58913"
                        name="慢性肝病"
                        shape="square"
                        :disabled="
                          noHistory && formData.medicalHistoryArr.length > 0
                        "
                        >慢性肝病</van-checkbox
                      >
                    </van-col>
                    <van-col span="12">
                      <van-checkbox
                        checked-color="#D58913"
                        name="免疫缺陷类疾病"
                        shape="square"
                        :disabled="
                          noHistory && formData.medicalHistoryArr.length > 0
                        "
                        >免疫缺陷类疾病</van-checkbox
                      >
                    </van-col>
                    <van-col span="12">
                      <van-checkbox
                        checked-color="#D58913"
                        name="其他"
                        shape="square"
                        :disabled="
                          noHistory && formData.medicalHistoryArr.length > 0
                        "
                        >其他</van-checkbox
                      >
                    </van-col>
                  </van-row>
                </van-checkbox-group>
              </template>
            </van-field>
            <van-field
              readonly
              clickable
              is-link
              name="relationship_name"
              :value="formData.relationship_name"
              placeholder="点击选择"
              @click="pickerChange('relationship')"
              required
              :rules="[{ required: true, message: '请检查与户主关系' }]"
            >
              <template #label>
                <div class="field-title">与户主关系</div>
              </template>
            </van-field>
            <van-field
              readonly
              clickable
              is-link
              name="ascription"
              :value="formData.ascription"
              placeholder="点击选择"
              @click="pickerChange('ascription')"
              required
              :rules="[{ required: true, message: '请检查家庭所属区域' }]"
            >
              <template #label>
                <div class="field-title">家庭所属区域</div>
              </template>
            </van-field>
            <van-field
              v-model="formData.quarter"
              required
              clearable
              maxlength="20"
              :rules="[{ required: true, message: '请检查家庭所属小区' }]"
              name="quarter"
              placeholder="请输入家庭所属小区"
            >
              <template #label>
                <div class="field-title">家庭所属小区</div>
                <div class="field-text">(或无则住宅楼名)</div>
              </template>
            </van-field>
            <van-field
              v-model="formData.address"
              rows="3"
              autosize
              type="textarea"
              maxlength="255"
              placeholder="请输入详细地址"
              required
              :rules="[{ required: true, message: '请检查详细地址' }]"
            >
              <template #label>
                <div class="field-title">详细地址</div>
              </template>
            </van-field>
          </div>
        </div>
      </van-form>
    </div>

    <div class="bottom-bar">
      <van-button
        class="bottom-bar-btn"
        block
        size="large"
        color="#D58913"
        type="info"
        text="确认提交"
        @click="submitAction"
      />
    </div>
  </div>
</template>

<script>
import {
  getSexByIdCard,
  identityCodeValid,
  getBirthByIdCard,
} from '@/libs/tools'
import { saveStudentResident, getResidentInfo } from '@/api/school.js'
// import nationality from '@/views/school/dict/nationality'
import area from '@/views/school/dict/area'
import dict from '@/views/school/dict/others'

export default {
  props: {
    resident_id: {
      type: String,
      default: () => {
        return ''
      },
    },
  },
  data() {
    return {
      area,
      dict,
      // nationality,
      data: {},
      popupShow: false,
      minDate: new Date(1900, 0, 1),
      maxDate: new Date(),
      popupState: '',
      pickerType: '',
      pickerData: [],
      userData: {},
      disabled: {},
      formData: {
        medicalHistoryArr: [],
        // nationality_name: '中国，中华人民共和国',
        // nationality: 'CN',
        origin: '身份证',
        origin_name: '身份证',
        medicalHistoryArr: ['无'],
      },
      noHistory: false,
      cascaderShow: false,
      cascaderValue: '',
      cascadeOptions: [],
      origin_list: [
        { text: '身份证', value: '身份证' },
        { text: '其他', value: '其他' },
      ],
      fieldNames: {
        text: 'name',
        value: 'code',
        children: 'children',
      },
    }
  },

  components: {},

  computed: {
    isReadonly() {
      return !!this.resident_id
    },
  },

  watch: {},

  mounted() {
    this.route = this.$route.query
    this.init()
    this.cardNoChange()
  },

  methods: {
    cardNoChange() {
      // if (this.formData.nationality == 'CN' && this.formData.card_no) {
      if (this.formData.origin == '身份证' && this.formData.card_no) {
        let cardNo = this.cardNoValidator(this.formData.card_no)
        if (cardNo == false) {
          this.failNotice('请检查身份证号')
        } else {
          let sex = getSexByIdCard(this.formData.card_no)
          if (sex) this.$set(this.formData, 'sex', sex.code)
          let birth = getBirthByIdCard(this.formData.card_no)
          if (birth) this.$set(this.formData, 'birthday', birth)
        }
      }
    },
    async init() {
      // 获取区域所属
      let options = this.$common.xeUtils.toArrayTree(this.area, {
        strict: true,
        parentKey: 'parent_id',
        key: 'id',
        children: 'children',
      })
      this.cascadeOptions = options[0].children
      // 回显
      const info = await getResidentInfo({ id: this.resident_id })
      if (info.data.errcode == '0') {
        // console.log('回显', info.data.data)
        this.$set(this.formData, 'name', info.data.data.name)
        this.$set(this.formData, 'tel', info.data.data.tel)
        this.$set(this.formData, 'card_no', info.data.data.card_no)
        this.$set(this.formData, 'sex', info.data.data.sex)
        if (info.data.data.birthday) {
          this.$set(
            this.formData,
            'birthday',
            this.$common.xeUtils.toDateString(
              info.data.data.birthday,
              'yyyy-MM-dd'
            )
          )
        }
        // if (data.nationality) {
        //   this.$set(this.formData, 'nationality', data.nationality)
        //   this.$set(
        //     this.formData,
        //     'nationality_name',
        //     this.nationality.find((item) => item.value == data.nationality).text
        //   )
        // }
        if (data.origin) {
          this.$set(this.formData, 'origin', data.origin)
          this.$set(
            this.formData,
            'origin_name',
            this.origin_list.find((item) => item.value == data.origin).text
          )
        }
        if (info.data.data.relationship) {
          this.$set(this.formData, 'relationship', info.data.data.relationship)
          this.$set(
            this.formData,
            'relationship_name',
            this.dict.relationship.find(
              (item) => item.value == info.data.data.relationship
            ).text
          )
        }
        if (info.data.data.medical_history) {
          this.$set(
            this.formData,
            'medicalHistoryArr',
            info.data.data.medical_history.split(',')
          )
          this.$set(
            this.formData,
            'medical_history',
            info.data.data.medical_history
          )
        }
        this.$set(this.formData, 'area_code', info.data.data.area_code)
        this.$set(this.formData, 'area_name', info.data.data.area_name)
        this.$set(this.formData, 'street_code', info.data.data.street_code)
        this.$set(this.formData, 'street_name', info.data.data.street_name)
        this.$set(
          this.formData,
          'community_code',
          info.data.data.community_code
        )
        this.$set(
          this.formData,
          'community_name',
          info.data.data.community_name
        )
        this.$set(this, 'cascaderValue', info.data.data.community_code)
        if (
          info.data.data.area_name &&
          info.data.data.street_name &&
          info.data.data.community_name
        ) {
          this.$set(
            this.formData,
            'ascription',
            info.data.data.area_name +
              '/' +
              info.data.data.street_name +
              '/' +
              info.data.data.community_name
          )
        }
        this.$set(this.formData, 'quarter', info.data.data.quarter)
        this.$set(this.formData, 'address', info.data.data.address)
        this.medicalHistoryChange(this.formData.medicalHistoryArr)
      }
    },
    pickerChange(type) {
      switch (type) {
        case 'date':
          this.popupState = 'datePicker'
          this.pickerType = 'date'
          this.popupShow = true
          break
        case 'ascription':
          this.popupState = 'cascader'
          this.pickerType = 'ascription'
          this.popupShow = true
          break
        case 'relationship':
          this.popupState = 'picker'
          this.pickerType = 'relationship'
          this.pickerData = this.dict.relationship
          this.popupShow = true
          break
        // case 'nationality':
        //   this.popupState = 'picker'
        //   this.pickerType = 'nationality'
        //   this.pickerData = this.nationality
        //   this.popupShow = true
        //   break
        case 'origin':
          this.popupState = 'picker'
          this.pickerType = 'origin'
          this.pickerData = this.origin_list
          this.popupShow = true
          break
      }
    },
    pickerConfirm(e) {
      switch (this.pickerType) {
        case 'relationship':
          this.formData.relationship_name = e.text
          this.formData.relationship = e.value
          this.popupShow = false
          break
        // case 'nationality':
        //   this.formData.nationality_name = e.text
        //   this.formData.nationality = e.value
        //   this.popupShow = false
        //   this.cardNoChange()
        //   break
        case 'origin':
          this.formData.origin_name = e.text
          this.formData.origin = e.value
          this.popupShow = false
          this.cardNoChange()
          break
      }
    },
    pickerCancel(e) {
      switch (this.pickerType) {
        case 'relationship':
          this.formData.relationship_name = ''
          this.formData.relationship = ''
          this.popupShow = false
          break
        // case 'nationality':
        //   this.formData.nationality_name = ''
        //   this.formData.nationality = ''
        //   this.popupShow = false
        //   break
        case 'origin':
          this.formData.origin_name = ''
          this.formData.origin = ''
          this.popupShow = false
          break
      }
    },
    cascaderFinish({ value, selectedOptions, tabIndex }) {
      this.formData.ascription =
        selectedOptions[0].name +
        '/' +
        selectedOptions[1].name +
        '/' +
        selectedOptions[2].name
      this.formData.area_code = selectedOptions[0].code
      this.formData.street_code = selectedOptions[1].code
      this.formData.community_code = selectedOptions[2].code
      this.formData.area_name = selectedOptions[0].name
      this.formData.street_name = selectedOptions[1].name
      this.formData.community_name = selectedOptions[2].name
      this.popupShow = false
    },
    cascaderClose() {
      this.formData.ascription = ''
      this.formData.area_code = ''
      this.formData.street_code = ''
      this.formData.community_code = ''
      this.formData.area_name = ''
      this.formData.street_name = ''
      this.formData.community_name = ''
      this.popupShow = false
    },
    datePickerConfirm(e) {
      this.formData.birthday = this.$common.xeUtils.toDateString(
        e,
        'yyyy-MM-dd'
      )
      this.popupShow = false
    },
    datePickerCancel(e) {
      this.formData.birthday = ''
      this.popupShow = false
    },
    searchChange(type) {
      switch (type) {
        // case 'nationality':
        //   if (this.data.search) {
        //     this.pickerData = this.$common.xeUtils.filter(
        //       this.nationality,
        //       (item) => item.text.match(this.data.search)
        //     )
        //   } else {
        //     this.pickerData = this.nationality
        //   }
        //   break
        case 'origin':
          if (this.data.search) {
            this.pickerData = this.$common.xeUtils.filter(this.origin, (item) =>
              item.text.match(this.data.search)
            )
          } else {
            this.pickerData = this.origin_list
          }
          break
      }
    },
    medicalHistoryChange(e) {
      for (let i = 0; i < e.length; i++) {
        if (e[i] == '无') {
          this.noHistory = true
          return
        } else {
          this.noHistory = false
          return
        }
      }
    },
    failNotice(msg) {
      this.$notify({ type: 'danger', message: msg })
    },
    onFailed(errorInfo) {
      this.failNotice(errorInfo.errors[0].message)
    },
    // 身份证校验
    cardNoValidator(val) {
      const reg = identityCodeValid(val)
      if (!reg.pass) return false
    },
    submitAction() {
      this.$refs.form.submit()
    },
    onSubmit() {
      if (this.formData.medicalHistoryArr) {
        this.formData.medical_history =
          this.formData.medicalHistoryArr.join(',')
      }
      // 校验
      // if (!this.formData.temp) {
      //   this.failNotice('请输入体温')
      //   return false
      // } else {
      //   if (!identityTemp(this.formData.temp)) {
      //     this.failNotice('请输入正确体温')
      //     return false
      //   }
      // }
      this.$dialog
        .confirm({
          title: '是否确认提交',
          message: '',
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          confirmButtonColor: '#D58913',
          beforeClose: async (action, done) => {
            if (action === 'confirm') {
              const param = {
                ...this.formData,
                parent_id: this.route.parent_id,
                student_id: this.route.student_id,
                teacher_id: this.route.teacher_id,
                workers_id: this.route.workers_id,
                id: this.resident_id,
              }
              // console.log('最终提交信息', param)
              const insertData = await saveStudentResident(param)
              if (insertData.data.errcode == 0) {
                this.$toast('操作成功')
                setTimeout(() => {
                  this.formData = {}
                  this.$emit('getResident')
                }, 500)
                done()
              } else {
                this.$toast(insertData.data.errmsg)
                done()
              }
            } else {
              done()
            }
          },
        })
        .catch(() => {})
    },
  },
}
</script>

<style lang="less" scoped>
.resident /deep/ .van-checkbox {
  min-height: 30px;
}

.resident /deep/ .van-field__label span {
  display: inline-block;
  padding-left: 5px;
  width: 90%;
  text-align-last: justify;
}

.resident {
  background: #f2f7fb;
  width: 100%;
  box-sizing: border-box;

  &-inner {
    padding: 20px 20px 0;
    .card {
      background: inherit;

      &-container {
        border-radius: 10px;
        overflow: hidden;
        background-color: white;
        padding: 10px;
      }
    }
  }

  .bottom-bar {
    position: fixed;
    bottom: 0;
    width: 100%;
    &-btn {
    }
  }
}
.field-title {
  display: inline-block;
  padding: 0 5px;
  font-size: 12px;
  width: 100%;
  text-align-last: justify;
  text-align: justify;
  box-sizing: border-box;
  line-height: 0px !important;
}
.field-title:after {
  content: '';
  display: inline-block;
  width: 100%;
  overflow: hidden;
}
.field-text {
  padding: 0 5px;
  font-size: 12px;
}
</style>
